package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.*;
import com.itheima.service.mongo.MovementService;
import com.itheima.utils.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Guanxing
 * @date 2021/9/22
 */
@Service
public class MovementServiceImpl implements MovementService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    //发布动态
    @Override
    public void saveMovement(Movement movement) {
        //保存到详情表
        movement.setCreated(System.currentTimeMillis());
        movement.setPid(idService.getNextId(ConstantUtil.MOVEMENT_ID));//mongo使用自增id
        mongoTemplate.save(movement);

        //保存到自己的动态表
        MyMovement myMovement = new MyMovement();
        myMovement.setCreated(System.currentTimeMillis());
        myMovement.setPublishId(movement.getId());
        mongoTemplate.save(myMovement, ConstantUtil.MOVEMENT_MINE + movement.getUserId());

        //查找我的好友
        Query query = new Query(
                Criteria.where("userId").is(movement.getUserId())
        );
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //将动态保存到好友动态表中
        if (CollectionUtil.isNotEmpty(friendList)) {
            for (Friend friend : friendList) {
                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setCreated(System.currentTimeMillis());
                friendMovement.setUserId(movement.getUserId());
                friendMovement.setPublishId(movement.getId());
                //将数据发送到好友的动态表中
                mongoTemplate.save(friendMovement, ConstantUtil.MOVEMENT_FRIEND + friend.getFriendId());
            }
        }
    }

    //根据id查询我的动态
    @Override
    public PageBeanVo findMovementByUserId(Integer pageNum, Integer pageSize, Long userId) {
        int startIndex = (pageNum - 1) * pageSize;
        //根据id查询我所有的动态
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(startIndex).limit(pageSize);
        List<MyMovement> myMovementList = mongoTemplate.find(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);

        List<Movement> movementList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(myMovementList)) {
            for (MyMovement myMovement : myMovementList) {
                //根据主键查询动态详情
                Movement movement = mongoTemplate.findById(myMovement.getPublishId(), Movement.class);
                movementList.add(movement);
            }
        }

        //查询记录总数
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_MINE + userId);

        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    //查询好友动态
    @Override
    public PageBeanVo findFriendMovement(Integer pageNum, Integer pageSize, Long userId) {
        int startIndex = (pageNum - 1) * pageSize;
        //根据userId查询好友发布的动态id
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("create")))
                .skip(startIndex).limit(pageSize);
        List<FriendMovement> friendMovementList = mongoTemplate.find(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);

        List<Movement> movementList = new ArrayList<>();
        //查询动态详情
        if (CollectionUtil.isNotEmpty(friendMovementList)) {
            for (FriendMovement friendMovement : friendMovementList) {
                Movement movement = mongoTemplate.findById(friendMovement.getPublishId(), Movement.class);
                movementList.add(movement);
            }
        }
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_FRIEND + userId);
        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    //查询推荐好友动态
    @Override
    public PageBeanVo findRecommendMovement(Integer pageNum, Integer pageSize, Long loginUserId) {
        int startIndex = (pageNum - 1) * pageSize;
        //根据userId查询推荐动态
        Query query = new Query(
                Criteria.where("userId").is(loginUserId)
        ).with(Sort.by(Sort.Order.desc("create")))
                .skip(startIndex).limit(pageSize);
        List<RecommendMovement> recommendMovementList = mongoTemplate.find(query, RecommendMovement.class);
        List<Movement> movementList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(recommendMovementList)) {
            for (RecommendMovement recommendMovement : recommendMovementList) {
                Movement movement = mongoTemplate.findById(recommendMovement.getPublishId(), Movement.class);
                movementList.add(movement);
            }
        }

        long counts = mongoTemplate.count(query, RecommendMovement.class);
        return new PageBeanVo(pageNum,pageSize,counts,movementList);
    }

    //单条动态
    @Override
    public Movement findMovementByMovementId(String movementId) {
        Movement movement = mongoTemplate.findById(movementId, Movement.class);
        return movement;
    }

    //查询动态列表
    @Override
    public PageBeanVo findMovementsByUserIdAndState(Integer pageNumber, Integer pageSize, Long uid, Integer stateInt) {
        int startIndex  = (pageNumber-1)*pageSize;
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(startIndex).limit(pageSize);
        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if (stateInt != null) {
            query.addCriteria(Criteria.where("state").is(stateInt));
        }

        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        long count = mongoTemplate.count(query, Movement.class);

        return new PageBeanVo(pageNumber,pageSize,count,movementList);
    }
    //保存通过-拒绝的信息
    @Override
    public void updateMovement(Movement movement) {
        mongoTemplate.save(movement);
    }
}
